package com.xin.libandroidpaysocial.pay.alipay;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.xin.libandroidpaysocial.pay.Constants;
import com.xin.libandroidpaysocial.pay.PayEventBusData;

import org.greenrobot.eventbus.EventBus;

/**
 * https://docs.open.alipay.com/204/105051/
 */
public class APay {
    private static int SDK_PAY_FLAG = 3560;
    private final Handler mHandler;
    Activity context;

    public APay(final Activity context) {
        this.context = context;
        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what == SDK_PAY_FLAG) {
                    if (msg.obj != null && msg.obj instanceof String) {
                        onResult((String) msg.obj);
                    }
                }
            }
        };
    }

    private void onResult(String obj) {
        /*https://docs.open.alipay.com/59/103665/*/
        PayResult result = new PayResult(obj);
        String resultStatus = result.getResultStatus();
        PayEventBusData payResult = new PayEventBusData(1);
        if (TextUtils.equals(resultStatus, "9000")) {
            payResult.setState(0);
            payResult.setMsg(Constants.PaySuccess);
        } else if (TextUtils.equals(resultStatus, "8000")) {
            payResult.setMsg("正在处理中");
        } else if (TextUtils.equals(resultStatus, "4000")) {
            payResult.setMsg("充值失败，请再次重试");
        } else if (TextUtils.equals(resultStatus, "5000")) {
            payResult.setMsg("重复请求");
        } else if (TextUtils.equals(resultStatus, "6001")) {
            payResult.setMsg("用户中途取消");
        } else if (TextUtils.equals(resultStatus, "6002")) {
            payResult.setMsg("网络连接出错");
        }
        EventBus.getDefault().post(payResult);
    }

    private void finish() {
        context.finish();
    }

    /**
     * 拼接后的
     *
     * @param payInfo
     */
    public void doPay(final String payInfo) {

        //异步处理
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                //新建任务
                PayTask alipay = new PayTask(context);
                //获取支付结果
                String result = alipay.pay(payInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    private void toast(String str) {
        Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
    }
}
